#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <stdint.h>
#include <unistd.h>
#include <time.h>
#include "patterns.h"

int open_port(void);
void write_port(int fd, uint8_t data);
void set_interface_attribs(int fd);

int main(void)
{
	//Set up serial port
	int fd;
	fd = open_port();
	set_interface_attribs(fd);

	//Set up sleep (to allow for page write cycles)
	//NOTE: cannot compile under c99 (nanosleep was
	//removed...)
	struct timespec delay;	
	delay.tv_sec = 0;
	delay.tv_nsec = 10000000; //10ms delay, as write cycle max is 6ms
	
	//Write to serial port
	/*
	int i, j;

	for (i = 0; i < 48; ++i) {
		for (j = 0; j < 32; ++j) {
			write_port(fd, pattern[j][i]);
		}
	}
	*/

	write_port(fd, 'A');

	//nanosleep(&delay, NULL);

	//write_port(fd, 'B');
	
	return 0;
}

//**********
//write_port
//**********

//Writes the opened serial port.

void write_port(int fd, uint8_t data)
{
	int n = write(fd, &data, 1);
	if (n < 0) {
		perror("write: unable to write data - ");
	}
}

//*********
//open_port
//*********

//Opens a serial port for reading and writing.

int open_port(void)
{
	int fd;

	fd = open("/dev/ttyUSB0", O_WRONLY | O_NOCTTY | O_NONBLOCK);
	if (fd == -1) {
		perror("open_port: Unable to open /dev/ttyUSB0 - ");
	}
	
	else {
		fcntl(fd, F_SETFL, 0);
	}

	return (fd);
}

//*********************
//set_interface_attribs
//*********************

//Sets options for the serial interface via termios struct.

void set_interface_attribs(int fd)
{
	struct termios options;

	//Fills in default/current options for those
	//that aren't explicitly set
	tcgetattr(fd, &options);

	cfsetispeed(&options, B38400);
	cfsetospeed(&options, B38400);
	
	options.c_cflag |= (CLOCAL | CREAD);
	
	//8-bit character size
	options.c_cflag &= ~CSIZE;
	options.c_cflag |= CS8;

	//Raw output
	options.c_oflag &= ~OPOST;

	tcsetattr(fd, TCSANOW, &options);

}
